package org.example.maven.service.Impl;

import com.github.pagehelper.PageHelper;
import io.micrometer.common.util.StringUtils;
import jakarta.persistence.EntityManager;
import org.apache.poi.ss.usermodel.Row;
import org.example.maven.mapper.classificationMapper;
import org.example.maven.mapper.collectionMapper;
import org.example.maven.mapper.eraMapper;
import org.example.maven.pojo.Review.ReviewCollectionListTable;
import org.example.maven.pojo.Review.ReviewCollectionSpecie;
import org.example.maven.pojo.list.ListTableCollection;
import org.example.maven.pojo.list.ListTableCollectionAddDetail;
import org.example.maven.pojo.list.ListTableCollectionDetail;
import org.example.maven.pojo.list.ListTableCollectionEditDetail;
import org.example.maven.pojo.utils.CollectionJpa;
import org.example.maven.pojo.utils.SearchCollection;
import org.example.maven.service.ClassificationService;
import org.example.maven.service.CollectionService;
import org.example.maven.utils.AliyunUtils;
import org.example.maven.utils.ExcelUtils;
import org.example.maven.utils.excel.ExcelRowParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Transactional
public class collectionServiceImpl implements CollectionService, ExcelRowParser<ListTableCollectionAddDetail> {
    @Autowired
    private collectionMapper collectionmapper;
    @Autowired
    private classificationMapper classificationMapper;
    @Autowired
    private eraMapper eraMapper;

    private final EntityManager entityManager;

    public collectionServiceImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
    @Override
    //分页查询藏品
    public List<ListTableCollection> getList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return collectionmapper.getAllList();
    }

    @Override
    public List<ListTableCollection> getAllCollection() {
        return collectionmapper.getAllList();
    }

    @Override
    public Integer getCollectionNumber(SearchCollection searchCollection) {
        return collectionmapper.getCollectionNumber(searchCollection);
    }

    @Override
    public List<ListTableCollection> getSpecificCollection(int pageNum, int pageSize, SearchCollection searchCollection) {
        PageHelper.startPage(pageNum, pageSize);
        return collectionmapper.getSpecificCollection(searchCollection);
    }

    @Override
    public ListTableCollectionDetail getCollectionDetail(Integer id) {
       return collectionmapper.getCollectionDetail(id);
    }

    @Override
    public ListTableCollectionEditDetail getCollectionEditDetailById(Integer id) {
        return collectionmapper.getCollectionEditById(id);
    }

    @Override
    public Integer getCollectionReview(ReviewCollectionSpecie reviewCollectionSpecie) {
        return collectionmapper.getCollectionReview(reviewCollectionSpecie);
    }

    @Override
    public Integer getCollectionReviewDay() {
        return collectionmapper.getCollectionReviewDay();
    }

    @Override
    public List<ReviewCollectionListTable> getCollectionReviewListTable(Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return collectionmapper.getReviewCollectionListTable();
    }

    @Override
    public List<ReviewCollectionListTable> getSpecieReviewCollection(Integer pageNum,Integer pageSize,ReviewCollectionSpecie reviewCollectionSpecie) {
        PageHelper.startPage(pageNum, pageSize);
        return collectionmapper.getSpecieReviewCollection(reviewCollectionSpecie);
    }

    @Override
    public void updateCollection(CollectionJpa collectionJpa) {
        entityManager.merge(collectionJpa);
    }

    @Override
    public void updateCollectionReview(Integer[] id) {
        collectionmapper.updateCollectionReview(id);
    }

    @Override
    public void addCollection(ListTableCollectionAddDetail listTableCollectionAddDetail) {
        collectionmapper.addCollection(listTableCollectionAddDetail);
        //entityManager.merge(collectionJpa);
    }

    @Override
    public void addReviewCollection(Integer collectionId, Integer userId) {
        collectionmapper.addReviewCollection(collectionId,userId);
    }


    @Override
    public ListTableCollectionAddDetail parse(Row row, int rowNum) throws Exception {
        ListTableCollectionAddDetail relic = new ListTableCollectionAddDetail();
        //从excel表格中获取数据
        relic.setInternalId(ExcelUtils.getCellStringValue(row.getCell(0)));//获取藏品编号
        relic.setName(ExcelUtils.getCellStringValue(row.getCell(1)));//获取藏品名字
        relic.setAlternateName(ExcelUtils.getCellStringValue(row.getCell(2)));//获取藏品别名
        relic.setClassificationId(classificationMapper.getClassificationIdBySubcategory(ExcelUtils.getCellStringValue(row.getCell(3))));//获取藏品分类
        relic.setEraId(eraMapper.getEraIdByEra(ExcelUtils.getCellStringValue(row.getCell(4))));//获取藏品年代
        relic.setDescription(ExcelUtils.getCellStringValue(row.getCell(5)));//获取藏品详情
        String cellValue = ExcelUtils.getCellStringValue(row.getCell(6));//获取藏品保存信息
        // 转换为枚举类型
        ListTableCollectionAddDetail.PreservationStatus status = ListTableCollectionAddDetail.PreservationStatus.fromChineseName(cellValue);
        relic.setPreservationStatus(status);
        // 修改为（安全转换）
        String weightStr = ExcelUtils.getCellStringValue(row.getCell(7));
        try {
            if (StringUtils.isBlank(weightStr)) {
                relic.setWeight(null);
            } else {
                relic.setWeight(new BigDecimal(weightStr));
            }
        } catch (NumberFormatException e) {
            System.out.println("第 " + rowNum + " 行重量格式错误，已重置为0");
            relic.setWeight(BigDecimal.ZERO); // 格式错误时强制设为0
        }
        relic.setCurrentLocation(ExcelUtils.getCellStringValue(row.getCell(8)));//获取藏品存放位置
        cellValue =ExcelUtils.getCellStringValue(row.getCell(9));//获取藏品状态
        ListTableCollectionAddDetail.CollectionStatus status1=ListTableCollectionAddDetail.CollectionStatus.fromChineseName(cellValue);
        relic.setStatus(status1);
        Instant instant = Instant.ofEpochMilli(System.currentTimeMillis());//获取当前时间
        LocalDateTime loginTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        relic.setCreatedAt(loginTime);
        // 获取文件名（保持原有逻辑）
        String originalFileName = ExcelUtils.getCellStringValue(row.getCell(10));
        // 提交异步上传任务
        CompletableFuture<String> uploadFuture = AliyunUtils.asyncUpload(originalFileName);
        // 立即设置Future到对象中
        relic.setImgFuture(uploadFuture);
        System.out.println(relic);
        // 数据校验
        if (StringUtils.isBlank(relic.getName())) {
            throw new Exception("名称不能为空");
        }
        return relic;
    }
}
